import Path from 'path'
import webpack from 'webpack'
import webpackDevServer from 'webpack-dev-server'
import Koa from 'koa'
import Favicon from 'koa-favicon'
import StaticFile from 'koa-static'
import ejsEngine from 'koa-ejs'
import webpackConfig from '../webpack.config.js'
import config from './config'

const isDeveloping = config.env !== 'production'

const app = new Koa()
ejsEngine(app, {
  root: Path.join(__dirname, '/../views'),
  layout: 'tpl',
  viewExt: 'ejs',
  cache: !isDeveloping,
  debug: isDeveloping
})

const bundle = () => {
    let bundleStart = null;
    const compiler = webpack(webpackConfig);
    compiler.plugin('compile', () => {
      console.log('Bundling...');
      bundleStart = Date.now();
    });

  compiler.plugin('done', () => {
    console.log(`Bundled in ${Date.now() - bundleStart} ms!`);
  });

  const bundler = new webpackDevServer(compiler, {
    publicPath: webpackConfig.output.publicPath,
    historyApiFallback: true,
    hot: true,
    quiet: false,
    noInfo: true,
    stats: {
      colors: true
    }
  });

  bundler.listen(config.dev_hot_server_port, 'localhost', () => {
    console.log('Bundling project, please wait...');
  })
};

app.use(function*(next) {
  // 判断客户端的浏览器是否是移动端访问
  let deviceAgent = this.req.headers['user-agent'].toLowerCase()
  let agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/)
  this.clientInfo = {
    isMobile : agentID ? true : false
  }
  yield next
})

import { siteRouter } from './route/site'
import { devProxyRouter } from './route/dev_proxy'
import { prodProxyRouter } from './route/prod_proxy'

if (isDeveloping) {
  bundle()
  app.use(devProxyRouter.routes())
  // 静态目录访问路由,放在代理的后面,否则会出现在开发模式下面不会访问内存的js js/images/css
  app.use(StaticFile(__dirname + '/../public',{'maxage':1}))
} else {
  app.use(prodProxyRouter.routes())
  // 静态目录访问路由,放在代理的后面,否则会出现在开发模式下面不会访问内存的js js/images/css
  app.use(StaticFile(__dirname + '/../public',{'maxage':3*60*1000}))
}

// favico
app.use(Favicon(__dirname + '/../public/static/images/favicon.ico'))

app.use(siteRouter.routes())

// 服务器异常处理
if (config.env === 'test') {
  module.exports = app.callback();
} else {
  app.listen(config.listen_port)
  console.log(config.env)
}

app.on('error', function (err) {
  console.log(err.stack)
})

